const express = require('express');
//创建路由对象
const router = express.Router();

const path = require('path');
const db = require('../db.js');

//文件地址  admin/login.html --> url: /admin/login
router.get('/admin/login', (req, res) => {
    res.render(path.join(rootPath, 'view', 'admin/login.html'), {})
})

//检测用户登录信息
router.post('/admin/checkLogin', (req, res) => {
    //1. 接收数据 --- 用户名和密码
    const name = req.body.email;
    const pwd  = req.body.passwd;

    //2. 编写sQL语句 --- 验证用户名和密码是否正确的SQL语句
    const sql = 'select * from ali_admin where admin_email=? and admin_pwd=?';

    //3. 执行SQL语句
    db.query(sql, [name, pwd], (err, result) => {
        //4. 处理SQL结果 -- 返回登录成功或者失败的结果
        if (err) {
            console.log(err);
            return res.send({code:201, message:"登录失败"});
        }
        //当查询结果为1条数据时，说明用户名和密码正确，登录成功
        if (result.length == 1) {
            //登录成功 --- 将登录状态记录到session中
            //注册登录状态
            req.session.isLogin = true;
            //将当前登录的用户信息保存到 req.session.userInfo
            req.session.userInfo = result[0];

            res.send({code:200, message:"登录成功"});
        } else {
            res.send({code:202, message:"用户名或密码错误"});
        }
    })
})

//退出登录 --- 清除session
router.post('/admin/logout', (req, res) => {
    req.session.destroy();
    res.send({code:200, message:"退出登录成功"});
})

//显示后台首页（admin/index.html）
//文件地址  admin/index.html --> url: /admin/index
router.get('/admin/index', (req, res) => {
    res.render(path.join(rootPath, 'view', 'admin/index.html'), {})
})


module.exports = router;